<template>
    <div class="assetmodule-admindata">
        <Card :bordered="false">
            <Form ref="form" :model="form" :rules="ruleValidate" label-position="left" :label-width="80" style="width: 100%;">
                <FormItem label="值班领导" prop="leader">
                    <Select v-model="form.leader" placeholder="请选择值班领导">
                        <Option v-for="(item, index) in leaderList" :value="item.user_id" :key="index" v-if="item.teacher_idbelongs_to">{{ item.teacher_idbelongs_to.teacher_name.zh }}</Option>
                    </Select>
                </FormItem>
                <FormItem label="环节干部">
                    <Select v-model="form.cadre" multiple placeholder="请选择环节干部">
                        <Option v-for="(item, index) in cadreList" :value="item.user_id" :key="index" v-if="item.teacher_idbelongs_to">{{ item.teacher_idbelongs_to.teacher_name.zh }}</Option>
                    </Select>
                </FormItem>
                
            </Form>
        </Card>
        <Card v-for="(item, index) in form.data" :key="index" style="margin-top: 10px;">
            <h3 slot="title">{{ item.label }}</h3>
            <div class="admin-duty-card" v-for="(iten, num) in item.value" :key="num">
                <div class="admin-duty-card-item">{{ iten.label }}</div>
                <div style="margin-right:20px;">
                    <Input v-model="iten.explain.zh">
                    <span slot="prepend">备注</span>
                    </Input>
                </div>
                <div class="admin-duty-card-btn">
                    <Button size="small" type="info" @click="editData(iten, item.label, index, num)">编辑</Button>
                </div>
            </div>
        </Card>
    
        <Button type="info" style="margin: 20px 0;" @click="handleSubmit('form')" :loading="butloading">保存数据</Button>
    
        <Modal v-model="dataModal" @on-ok="addData">
            <div slot="header">
                <Breadcrumb>
                    <BreadcrumbItem>{{ topTitle }}</BreadcrumbItem>
                    <BreadcrumbItem>{{ butTitle }}</BreadcrumbItem>
                </Breadcrumb>
            </div>
            <Form :model="forms" label-position="left" :label-width="80">
                <FormItem label="值班时间">
                    <DatePicker v-model="forms.time" type="datetime" placeholder="请选择值班时间"></DatePicker>
                </FormItem>
    
                <FormItem label="现场资料">
                    <Upload multiple :on-success="handleSuccess" :format="['jpg','jpeg','png']" ref="adminUpload" :on-format-error="handleFormatError" :headers="headers" accept="image/*" :action="picurl">
                        <Button type="ghost" icon="ios-cloud-upload-outline">上传资料</Button>
                    </Upload>
                </FormItem>
    
                <FormItem label="备注">
                    <Input v-model="forms.explain.zh" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入备注信息"></Input>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>

<script>

    export default {
        props: {
            condition: {
                type: [Boolean, Number],
                default: false
            }
        },
        data() {
            return {
                dataModal: false,
                topTitle: '',
                butTitle: '',
                srcUrl: null,
                headers: {
                'Authorization': 'Bearer '+((localStorage.token)?(localStorage.token):'')
                },
                picurl: this.$project.axios.baseUrl + 'api/user/v1/upload',
                butloading: false,
                tableUrl: 'api/watchlist/v1/get/adminin/indexrde',    
                leaderList: [],
                cadreList: [],
                moralList:[],
                leaderUrl: 'api/teacher/v1/get/dutyleader/list?type=1',
                cadreUrl: 'api/teacher/v1/get/cadreonduty/list?type=2',
                form: {
                    data_log_id: null,
                    leader: null,
                    cadre: [],
                    data: [],
                    
                },
                forms: {
                    file_cache_id: [],
                    time: '',
                    explain: {
                        zh: '',
                        mn: '',
                        en: ''
                    }
                },
                ruleValidate: {
                    leader: [{
                        required: true,
                        type: 'number',
                        message: '请选择值班领导',
                        trigger: 'change'
                    }],
                },
                active1: null,
                active2: null,    
                addUrl: 'api/watchlist/v1/admininspecttermdata/add',
                editUrl: 'api/watchlist/v1/admininspecttermdata/edit',
                selUrl: `api/watchlist/v1/admininspecttermdata/info/${this.condition}`
            }
        },
        methods: {
    
            /************************************************************
             * 
             * 上传成功              
             * 
             ************************************************************/
            handleSuccess(res, file) {
                this.forms.file_cache_id.push(res.data.id)
            },
    
            /************************************************************
             * 
             * 上传失败              
             * 
             ************************************************************/
            handleFormatError(file) {
                this.$Notice.warning({
                    title: '上传失败',
                    desc: 'File format of ' + file.name + ' is incorrect, please select jpg or png.'
                });
            },
    
            /************************************************************
             * 
             * 表单验证              
             * 
             ************************************************************/
            handleSubmit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.butloading = true
                        this.handelData()
                    } else {
                        this.$Message.error('请检查选择值班领导!');
                    }
                })
            },
    
            /************************************************************
             * 
             * 处理添加数据              
             * 
             ************************************************************/
            handelData() {
                let data = Object.assign({}, this.form)
                let form = {
                    leader: data.leader,
                    cadre: data.cadre,
                    data: []
                }
                if (this.condition) form['data_log_id'] = data.data_log_id
                data.data.forEach(item => {
                    item.value.forEach(el => {
                        delete el.label
                        form.data.push(el)
                    })
                })
                if (this.condition !=null) {
                    this.editSubmit(form)
                } else {
                    this.addSubmit(form)
                }
            },
    
            /************************************************************
             * 
             * 添加数据              
             * 
             ************************************************************/
            addSubmit(data) {
                this.$http.post(this.addUrl, data).then(val => {
                    this.butloading = false
                    this.$emit('requery', true)
                }).catch(err => {
                    this.butloading = false
                })
            },
    
            /************************************************************
             * 
             * 修改数据              
             * 
             ************************************************************/
            editSubmit(data) {
                this.butloading = false
                this.$http.post(this.editUrl, data).then(val => {
                    this.butloading = false
                    this.$emit('requery', true)
                }).catch(err => {
                    this.butloading = false
                })
            },
    
            /************************************************************
             * 
             * 保存当前数据              
             * 
             ************************************************************/
            addData() {
                let data = Object.assign({}, this.forms)
                this.form.data[this.active1].value[this.active2].explain = data.explain
                this.form.data[this.active1].value[this.active2].file_cache_id = data.file_cache_id
                this.form.data[this.active1].value[this.active2].time = data.time
                this.form.data[this.active1].value[this.active2].file_cache_id = [...data.file_cache_id]
                this.forms.file_cache_id = []
            },
    
            /************************************************************
             * 
             * 添加或修改数据              
             * 
             ************************************************************/
            editData(data, label, a, b) {
                this.$refs.adminUpload.clearFiles()
                this.topTitle = label
                this.butTitle = data.label
                this.forms.time = data.time
                this.forms.explain = data.explain
                this.active1 = a
                this.active2 = b
                this.dataModal = true
            },
    
            /************************************************************
             * 
             * 行政值班领导              
             * 
             ************************************************************/
            leaderData() {
                this.$http.get(this.leaderUrl).then(val => {
                    this.leaderList = val.data
                }).catch(err => {})
            },
    
            /************************************************************
             * 
             * 行政值班环节干部         
             * 
             ************************************************************/
            cadreData() {
                this.$http.get(this.cadreUrl).then(val => {
                    this.cadreList = val.data
                }).catch(err => {})
            },
            
            /************************************************************
             * 
             * 行政值班检查项列表              
             * 
             ************************************************************/
            tableData() {
                this.$http.get(this.tableUrl).then(val => {
                    this.form.data = val.data.map(el => ({
                        label: el.administrativeduty_name.zh,
                        value: this.handelFormData(el.admininspectterm, el.administrativeduty_id)
                    }))
                    if (this.condition) this.selData()
                }).catch(err => {})
            },
    
            /************************************************************
             * 
             * 处理请求过来的数据              
             * 
             ************************************************************/
            handelFormData(data, val) {
                let times = this.$dateTime()
                return data.map(el => ({
                    label: el.administrativeduty_name.zh,
                    administrativeduty_id: val,
                    admininspectterm_id: el.admininspectterm_id,
                    file_cache_id: [],
                    time: times,
                    explain: {
                        zh: '无',
                        mn: '',
                        en: ''
                    }
                }))
            },
    
            /************************************************************
             * 
             * 查询已添加数据         
             * 
             ************************************************************/
            selData() {
                this.$http.get(this.selUrl).then(val => {
                    this.form.leader = parseInt(val.data.leader)
                    
                    this.form.data_log_id = val.data.data_log_id
                    
                                 
                    this.form.data = val.data.data.map(el => ({
                        label: el.administrativeduty_name.zh,
                        value: this.handelFormData1(el.admininspectterm, el.administrativeduty_id)
                    }))                   
                    val.data.cadredata.map(res=>{
                        this.form.cadre.push(res.cadredata.user_id)
                    })
                }).catch(err => {})
            },
            handelFormData1(data, val) {
                return data.map(el => ({
                    label: el.administrativeduty_name.zh,
                    administrativeduty_id: val,
                    admininspectterm_id: el.admininspectterm_id,
                    file_cache_id: el.img,
                    time: el.time,
                    explain: el.explain
                }))
            },
            createdData() {
                this.$http.get("api/user/v1/user/info").then(val => {  
                    let res = val.data
                    if (res.length != 0) {
                        let user = parseInt(res.id)
                        let index = this.leaderList.findIndex(item => {
                            return item.user_id == user
                        })
                        if (index >= 0) {
                            this.form.leader = parseInt(res.id)
                        } else {
                            this.form.leader = ''
                        }
                    }
                });
            }
        },
        created() {
            let userinfo = localStorage.getItem('user_info') || false
            if (userinfo) {
                let id = JSON.parse(userinfo)
                this.form.leader = id.id
            }
            this.tableData()
            this.leaderData()
            this.cadreData()
            this.createdData()
        },
    }
</script>

<style lang="less">
    .assetmodule-admindata {
        width: 100%;
        height: 100%;
        position: relative;
        .admin-duty-card {
            display: flex;
            margin-top: 10px;
            &:first-of-type {
                margin: 0;
            }
            &-item {
                flex: 1;
            }
            &-btn {
                min-width: 45px;
                max-width: 45px;
                flex: 1;
            }
        }
    }
</style>
